package com.jjwxc.jwjskandriod.framework.widget;

import android.content.Context;
import android.graphics.Point;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.jjwxc.jwjskandriod.R;

/**
 * 悬浮窗常规状态
 */
public class RoundWindowSmallView extends LinearLayout {
    private static final String TAG = "RoundView";

    private final WindowManager windowManager;

    private WindowManager.LayoutParams mParams;

    private float mPrevX;
    private float mPrevY;
    private int mWidth;
    private final int mHeight;

    private long mLastTouchDownTime;  // 按下的时间
    private long lastClickTime;


    public RoundWindowSmallView(final Context context) {
        super(context);
        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        mWidth = getContext().getResources().getDisplayMetrics().widthPixels;
        mHeight = getContext().getResources().getDisplayMetrics().heightPixels;

        Point point = new Point();
        if (windowManager != null) {
            windowManager.getDefaultDisplay().getRealSize(point);
            mWidth = point.x;
            // mHeight =point.y;
        }

        // 获取布局文件
        LayoutInflater.from(context).inflate(R.layout.round_view, this);


        this.setOnTouchListener((view, motionEvent) -> {
            switch (motionEvent.getActionMasked()) {
                case MotionEvent.ACTION_DOWN:   // 按下
                    mLastTouchDownTime = System.currentTimeMillis();
                    mPrevX = motionEvent.getRawX();
                    mPrevY = motionEvent.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    float deltaX = motionEvent.getRawX() - mPrevX;
                    float deltaY = motionEvent.getRawY() - mPrevY;
                    mParams.x += deltaX;
                    mParams.y += deltaY;
                    mPrevX = motionEvent.getRawX();
                    mPrevY = motionEvent.getRawY();

                    // 判断是否越界
                    if (mParams.x < 0) mParams.x = 0;
                    if (mParams.x > mWidth - view.getWidth())
                        mParams.x = mWidth - view.getWidth();
                    if (mParams.y < 0) mParams.y = 0;
                    if (mParams.y > mHeight - view.getHeight())
                        mParams.y = mHeight - view.getHeight();

                    try {
                        assert windowManager != null;
                        windowManager.updateViewLayout(view, mParams);
                    } catch (Exception e) {
                        Log.d(TAG, e.toString());
                    }

                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:  // 松开
                    if (isOnClickEvent()) {
                        view.performClick();
                        // 添加点击事件
                        if (isFastDoubleClick()) {
                            // 防止连续点击，如果连续点击这里什么也不做
                        } else {
                            // Toast.makeText(context, "你点击了悬浮球", Toast.LENGTH_SHORT).show();
                            new Handler().post(() -> RoundView.getInstance().performClick());
                            return false;
                        }
                    }
                    break;

            }

            return false;
        });
    }

    @Override
    public boolean performClick() {
        return super.performClick();
    }

    /**
     * 将小悬浮窗的参数传入，用于更新小悬浮窗的位置
     *
     * @param params 小悬浮窗的参数
     */
    public void setParams(WindowManager.LayoutParams params) {
        mParams = params;
    }


    // 防止连续点击
    private boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {   // 点击间隔设置大于动画执行时间，避免重复点击造成多次执行动画
            return true;
        }
        lastClickTime = time;
        return false;
    }

    protected boolean isOnClickEvent() {
        // 少于150毫秒算点击事件
        int TOUCH_TIME_THRESHOLD = 150;
        return System.currentTimeMillis() - mLastTouchDownTime < TOUCH_TIME_THRESHOLD;
    }

    public void setVisibilityState(int state) {
        this.setVisibility(state);
    }
}
